<?php

namespace app\admin\controller\sign_up;

use app\common\controller\Backend;
use think\Db; 
//use think\Env;
use app\admin\library\OfficeConverter;
//use app\admin\library\pdf_to_images;
/**
 * 选方案
 *
 * @icon fa fa-circle-o
 */
class Programme extends Backend
{

    /**
     * Programme模型对象
     * @var \app\admin\model\sign_up\Programme
     */
    protected $model = null;
    //protected $modelValidate = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\sign_up\Programme;
        $this->view->assign("peopleNumberList", $this->model->getPeopleNumberList());
        $this->view->assign("daysList", $this->model->getDaysList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $course_type_purpose = Db::name('course_type_purpose')->select();

        $this->view->assign("purposeList", $course_type_purpose);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        $this->dataLimit = false;
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    //->with(['type','purpose'])
                    ->with(['purpose'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','title','image','people_number','days','paid_view','paid_download','createtime']);
//                $row->visible(['type']);
//				$row->getRelation('type')->visible(['title']);
				$row->visible(['purpose']);
				$row->getRelation('purpose')->visible(['title']);
            }
    
            //print_r(collection($list->items())->toArray());exit;
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);
                if($params['course_type_purpose_id'])
                {
                    $params['course_type_purpose_id'] = implode(',',$params['course_type_purpose_id']);
                }

                if($params['paid_download']>30)
                {
                    $this->error('付费下载价格不能大于30元');
                }
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $id = $this->model->getLastInsID();
                    if($params['file']!='')
                    {
                        $ppt_url = ROOT_PATH . 'public' .str_replace('/', DS, $params['file']);
                        $pathArr = explode('/',$params['file']);
    
                        $new_url = ROOT_PATH . 'public';
    
                        $save_url = '';
    
                        for ($i=1;$i<count($pathArr)-1;$i++)
                        {
                            $new_url.='\\'.$pathArr[$i];
                            $save_url.= '\\'.$pathArr[$i];
                        }
                        if(PHP_OS=='Linux')
                        {
                            $list = $this->pptLinux($ppt_url,$new_url,$save_url,$id,'programme_add');
                          
                        }
                        else
                        {
                            $list = $this->ppt($ppt_url,$new_url,$save_url);
                        }
                        $images = '';
                       
                        if($list)
                        {
                            $images=implode(',',$list);
                        }
                        if($images!='')
                        {
                            $this->model->allowField(true)->save(['images'=>$images],['id' => $id]);
                        }
                        
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $pptFile = $row['file'];
        $images = $row['images'];

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            if($params['course_type_purpose_id'])
            {
                $params['course_type_purpose_id'] = implode(',',$params['course_type_purpose_id']);
            }
            if ($params) {
                $params = $this->preExcludeFields($params);
                if($params['paid_download']>30)
                {
                    $this->error('付费下载价格不能大于30元');
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);

                        $result = $this->validate($params,$validate);

                        if (true !== $result) {
                            // 验证失败 输出错误信息
                            $this->error($result);
                        }
                    }


                    if($params['file']!='' && $params['file']!=$pptFile)
                    {

                        $ppt_url = ROOT_PATH . 'public' .str_replace('/', DS, $params['file']);
                        $pathArr = explode('/',$params['file']);

                        $new_url = ROOT_PATH . 'public';

                        $save_url = '';

                        for ($i=1;$i<count($pathArr)-1;$i++)
                        {
                            $new_url.='\\'.$pathArr[$i];
                            $save_url.= '\\'.$pathArr[$i];
                        }

                        if(PHP_OS=='Linux')
                        {
                            $list = $this->pptLinux($ppt_url,$new_url,$save_url,$ids,'programme_edit');
                          
                        }
                        else
                        {
                            $list = $this->ppt($ppt_url,$new_url,$save_url);
                        }
                       
                        if($list)
                        {
                            $params['images']=implode(',',$list);
                        }
                        if($images!='')
                        {
                            $old_image = explode(',',$images);
                            foreach($old_image as $k=>$v)
                            {
                                $un_path = ROOT_PATH . 'public' .str_replace('/', DS, $v);
                                if(file_exists($un_path))
                                {
                                    chmod($un_path,0777);
                                    unlink($un_path);
                                }

                            }
                            $pptDs = ROOT_PATH . 'public' .str_replace('/', DS, $pptFile);
                            if(file_exists($pptDs))
                            {
                                chmod($pptDs,0777);
                                unlink($pptDs);
                            }


                        }

                        /*$s = $this->pdf2png($ppt_url,$new_url,$save_url,-1);
                        if($s)
                        {
                            $params['images']=implode(',',$s);
                        }

                        if($images!='')
                        {
                            $old_image = explode(',',$images);
                            foreach($old_image as $k=>$v)
                            {
                                $un_path = ROOT_PATH . 'public' .str_replace('/', DS, $v);
                                if(file_exists($un_path))
                                {
                                    chmod($un_path,0777);
                                    unlink($un_path);
                                }

                            }
                        }*/

                    }
                    $result = $row->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function ceshi()
    {
        return $this->view->fetch();
        print_r(phpinfo());exit;
        $pdf_url = '/www/ceshi.pdf';
        $new_url = '/www';
        $save_url = '/www';
        $s = $this->pdf2png($pdf_url,$new_url,$save_url,0);

        print_r($s);exit;


    }


    public function ppt($file,$uploadsFolder,$save_url)
    {

        $data = [];
        $powerpnt = new \COM("powerpoint.application") or die("Unable to instantiate Powerpoint");

        //$file = $_SERVER['DOCUMENT_ROOT'].'/12.ppt';

        $presentation = $powerpnt->Presentations->Open(realpath($file), false, false, false) or die("Unable to open presentation");

        foreach($presentation->Slides as $slide)
        {
            //$slideName = "Slide2_" . $slide->SlideNumber;
            $slideName = md5($slide->SlideNumber.time());

            //$uploadsFolder = $_SERVER['DOCUMENT_ROOT'];
            $exportFolder = realpath($uploadsFolder);

            $data[] = str_replace('\\', '/', $save_url.'/'.$slideName.".jpg");
            $slide->Export($exportFolder."//".$slideName.".jpg", "jpg", "600", "400");
        }

        $presentation->Close();

        //$powerpnt->Quit();

        $powerpnt = null;
        return $data;
    }
    
    
    
    public function ceshi2()
    {
        $powerpnt = new \COM("powerpoint.application") or die("Unable to instantiate Powerpoint");

        $file = $_SERVER['DOCUMENT_ROOT'].'/12.ppt';

        $presentation = $powerpnt->Presentations->Open(realpath($file), false, false, false) or die("Unable to open presentation");

        foreach($presentation->Slides as $slide)
        {
            $slideName = md5($slide->SlideNumber.time());

            $uploadsFolder = $_SERVER['DOCUMENT_ROOT'];
            $exportFolder = realpath($uploadsFolder);

            $slide->Export($exportFolder."//".$slideName.".jpg", "jpg", "600", "400");
        }

        $presentation->Close();

        //$powerpnt->Quit();

        $powerpnt = null;

    }
    
    
    public function pptLinux($ppt_path,$new_url,$save_url,$id,$model)
    {
      
        $data = [];
        //$id = 15;
        $converter = new OfficeConverter\OfficeConverter($ppt_path);
        $savePath = $_SERVER['DOCUMENT_ROOT'].'/'.$model.$id.'/';
        if(!is_dir($savePath))
       {
           mkdir($savePath,0777,true);
       }
       $result = $converter->convertTo($savePath.'/2.pdf');//prepOutput()方法已被改造 将ppt转为pdf
       
       $pdf_path = $savePath.'2.pdf';
        if(!file_exists($pdf_path)) //判断是否转换成功
        {
            return;
        }
        
        exec("convert {$pdf_path} {$savePath}".md5($id.time()).".jpg 2>&1",$result,$a);//将pdf转图片
        if($a==1){
            //图片转换失败
            return;
        }
        
        $handle=opendir($savePath)  OR die('path error!');
        while(($file=readdir($handle))!==false){
            if($file=="."||$file==".."||$file=="2.pdf"){
                continue;
            }
            $data[] = str_replace('\\', '/', $save_url.'/'.$file);
      
           copy($savePath.$file,str_replace('\\', '/', $new_url.'/'.$file));
        }
        $this->deldir($savePath);
        return $data;
    }
    
    public function ceshi3()
    {
        $ppt = './uploads/2.pdf';    
        $path="/www/test/"; 

       $converter = new OfficeConverter\OfficeConverter('/www/test/2.ppt');
       $id = 17;
       $savePath = $_SERVER['DOCUMENT_ROOT'].'/programme_'.$id.'/';
       //$this->deldir($savePath);
       
       if(!is_dir($savePath))
       {
           mkdir($savePath,0777,true);
       }
        $result = $converter->convertTo($savePath.'/2.pdf');//prepOutput()方法已被改造

        $pdf_path = $savePath.'2.pdf';
        if(!file_exists($pdf_path))
        {
            return;
        }
        exec("convert {$pdf_path} {$savePath}".md5(mt_rand(0,9999).time()).".jpg 2>&1",$result,$a);
        if($a==1){
            echo "失败了";
            exit();
        }
    
        $handle=opendir($savePath)  OR die('path error!');
        while(($file=readdir($handle))!==false){
            if($file=="."||$file==".."||$file=="2.pdf"){
                continue;
            }
           copy($savePath.$file,'/www/test/'.$file);
        }
     
        
    }
    
      function deldir($dir) {
      //先删除目录下的文件：
      $dh=opendir($dir);
      while ($file=readdir($dh)) {
        if($file!="." && $file!="..") {
          $fullpath=$dir."/".$file;
          if(!is_dir($fullpath)) {
              unlink($fullpath);
          } else {
              deldir($fullpath);
          }
        }
      }
     
      closedir($dh);
      //删除当前文件夹：
      if(rmdir($dir)) {
        return true;
      } else {
        return false;
      }
    }
  

    function pdf2png($pdf,$path,$save_url,$page=-1)
    {

        if(!extension_loaded('imagick'))
        {
            echo 1;exit;
            return false;
        }
        if(!file_exists($pdf))
        {
            echo 2;exit;
            return false;
        }
        $im = new \Imagick();

        $im->setResolution(180,180);
        $im->setCompressionQuality(100);

        if($page==-1)
        {
            $im->readImage($pdf);
        }
        else
        {
            $im->readImage($pdf."[".$page."]");
        }

        foreach ($im as $Key => $Var)
        {
            $Var->setImageFormat('png');
            $filename = $path."/". md5($Key.time()).'.png';
            $save_name = $save_url."/". md5($Key.time()).'.png';

            if($Var->writeImage($filename) == true)
            {
                $Return[] = str_replace('\\', '/', $save_name);
            }
        }
        $im->clear();
        $im->destroy();
        return $Return;
    }


   /* function pdf2png($pdf, $path)
    {

        if (!extension_loaded('imagick')) {

            return false;
        }

        if (!file_exists($pdf)) {
            return false;
        }

        $im = new \Imagick();

        $im->setResolution(120, 120); //设置分辨率 值越大分辨率越高
        $im->setCompressionQuality(100);

        $im->readImage($pdf);
        foreach ($im as $k => $v) {
            $v->setImageFormat('png');
            $fileName = $path . md5($k . time()) . '.png';
            if ($v->writeImage($fileName) == true) {
                $return[] = $fileName;
            }
        }
        return $return;

    }*/



}
